<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="$t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" top="20vh" width="450px" @close='close'>
    <div class="dialogContentBoxMaxHeight60">
      <el-form ref="form" :model="record" label-width="120px" :rules="rules" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('目的IPv4地址')" prop="ip_address">
          <el-input v-emoji v-model="record.ip_address" ref="ipAddress" style="width:215px;" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('掩码')" prop="ipv4_mask">
          <el-input v-emoji v-model="record.ipv4_mask" ref="ipv4Mask" style="width:215px;" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('网口')" prop="interface">
          <el-select v-model="record.interface" ref="interface" :placeholder="$t('请选择出接口')" clearable filterable size='small'>
            <el-option v-for="item in policyList" :disabled="item.enPortMode === 3" :key="item.strPhysicsName" :label="item.strPhysicsName" :value="item.strPhysicsName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('下一跳')" prop="nexthop">
          <el-input v-emoji v-model="record.nexthop" ref="nexthop" style="width:215px;" size='small'></el-input>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addIpv4 } from '@/api/network/highAvailability/hotMachine'
import { getPhysicalApiArray } from '@/api/network/api/physical'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'Ipv4Dialog',
  data () {
    var validateInterface = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    var validateIpv4 = (rule, value, callback) => {
      let regexp = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (!regexp.test(value)) {
        callback(new Error(this.$t('请输入正确的ip地址')))
      } else {
        callback()
      }
    }
    var validateMask = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (this.isValidMask(value)) {
        callback()
      } else {
        callback(new Error(this.$t('请输入正确的子网掩码')))
      }
    }
    return {
      dialogVisible: false,
      record: {
        ip_address: '',
        ipv4_mask: '',
        interface: '',
        nexthop: ''
      },
      recordCopy: {
        ip_address: '',
        ipv4_mask: '',
        interface: '',
        nexthop: ''
      },
      policyList: [],
      rules: {
        ip_address: [{ required: false, validator: validateIpv4, trigger: 'blur' }],
        interface: [{ required: false, validator: validateInterface, trigger: 'change' }],
        ipv4_mask: [{ required: false, validator: validateMask, trigger: 'blur' }]
      }
    }
  },
  methods: {
    init () {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['ipAddress', 'ipv4Mask', 'nexthop']
        const selectData = ['interface']
        inputClass(this.$refs, data)
        selectClass(this.$refs, selectData)
      })
      getPhysicalApiArray().then(res => {
        if (res.status === 0) {
          this.policyList = res.info
        }
      })
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let formData = JSON.parse(JSON.stringify(this.record))
          if (this.isValidMask(formData.ipv4_mask)) {
            formData.ipv4_mask = this.netLabelIframe(formData.ipv4_mask)
          }
          addIpv4(formData).then(res => {
            if (res.status === 0) {
              this.$message({
                message: this.$t('添加成功'),
                type: 'success'
              })
              this.close()
              this.$parent.hotMachineHandleClick()
            }
          })
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.policyList = []
      this.$refs.form.resetFields()
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    },
    // 验证子网掩码
    isValidMask (mask) {
      let reg = /^(254|252|248|240|224|192|128|0)\.0\.0\.0|255\.(254|252|248|240|224|192|128|0)\.0\.0|255\.255\.(254|252|248|240|224|192|128|0)\.0|255\.255\.255\.(255|254|252|248|240|224|192|128|0)$/
      return reg.test(mask)
    },
    // 整理网段下拉框内容
    netLabelIframe (mask) {
      // 把ip和掩码转换成二进制
      const binaryMask = mask.split('.').map(segment => parseInt(segment).toString(2).padStart(8, '0')).join('')
      // 计算掩码位数
      const maskLength = binaryMask.indexOf('0') === -1 ? 32 : binaryMask.indexOf('0')
      return maskLength
    }
  }
}
</script>
